<?php

namespace App\Admin\Console\Commands;

use App\Admin\Models\VueRouter;
use App\Admin\Models\SystemModel;
use App\Admin\Models\AdminPermission;
use Illuminate\Console\GeneratorCommand;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class ResourceDelCommand extends GeneratorCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = '
        admin:del-resource
        {slug : 数据表名称}
        {--force : 强制删除}
    ';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '删除前台和后台资源';

    /**
     * 当前正在生成的数据库表名
     *
     * @var string
     */
    protected $title;

    public static $updateConfirmTip = '是否确认删除？';

    protected $types = [
        'model', 'filter', 'request', 'resource', 'controller', 'showdoc', 'test',
    ];

    protected function getStub(){}

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        if (config()->get('app.env')=='production') {
            $this->warn('生产环境下不适用');
            return false;
        }
        $slug = $this->argument('slug');
        if (!Schema::hasTable($slug)) {
            $this->error("不存在到数据库表 [ {$slug} ]");
            return false;
        }
        if (!$this->option('force') && !$this->confirm(static::$updateConfirmTip, true)){
            return false;
        }
        $this->name = underlineToBar(Str::singular(Str::kebab($this->argument('slug'))));
        $comment = DB::getDoctrineSchemaManager()->listTableDetails($slug)->getComment();
        if (!$comment) {
            $this->title = $this->argument('slug');
        } else {
            $this->title = str_replace('表', '', $comment);
        }
        DB::beginTransaction();
        try {
            $this->delSystemModel();// 删除系统模型
            $this->delMigration();// 删除迁移文件
            $this->delDummyResource();// 删除资源文件
            $this->delFrontRoute();// 删除前端路由
            $this->delAdminMenu();// 删除后台菜单
            $this->delBackRoute();// 删除后端路由
            $this->delAdminPermission();// 删除后台权限
            DB::commit();
            return true;
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            DB::rollBack();  
            return false;
        }
    }

    /**
     * 删除系统模型
     */
    protected function delSystemModel()
    {
        $systemModel = app(SystemModel::class);
        $id = $systemModel->where('slug', $this->argument('slug'))->value('id');
        $systemModel->where('parent_id', $id)->forceDelete();
        $systemModel->where('id', $id)->forceDelete();
        $vueRouter = app(VueRouter::class);
        $vueRouter->where('path', "/system-models/{$id}/edit")->delete();
        $this->info("系统模型 [ {$this->title} ] 删除成功");
    }

    /**
     * 删除资源文件
     */
    protected function delDummyResource()
    {
        $name = trim($this->name);
        $dummyResource = Str::camel($name);
        $ucDummyResource = Str::ucfirst($dummyResource);
        $pluralKebabDummyResource = Str::plural(Str::kebab($name));
        foreach ($this->types as $type) {
            $type = Str::ucfirst($type);
            if ($type != 'Model') {
                $typeDummyResource = $ucDummyResource.$type;
            } else {
                $typeDummyResource = $ucDummyResource;
            }
            exec('find ./ -type f -iname "*'.$typeDummyResource.'*" -delete');
        }
        exec('find . -name "*'.$pluralKebabDummyResource.'*" -exec rm -rf {} +');
        $this->info("资源文件 [ {$this->title} ] 删除成功");
    }

    /**
     * 删除前端路由
     */
    protected function delFrontRoute()
    {
        $name = trim($this->name);
        $pluralKebabDummyResource = Str::plural(Str::kebab($name));
        // 删除后台路由
        $path = "resources/admin/src/views/pages.js";
        $routeTemplate = <<<EOT
          'dummy-resources': () => import('@v/dummy-resources/Index'),
          'dummy-resources/create': () => import('@v/dummy-resources/Form'),
          'dummy-resources/:id(\\\\d+)/edit': () => import('@v/dummy-resources/Form'),
          'dummy-resources/:id(\\\\d+)': () => import('@v/dummy-resources/Detail'),
        EOT;
        $content = $this->files->get($path);
        $routeTemplateArr = explode("\n", $routeTemplate);
        foreach ($routeTemplateArr as $key => $value) {
            $replace = str_replace('dummy-resources', $pluralKebabDummyResource, $value);
            $content = str_replace(PHP_EOL.$replace, '', $content);
        }
        $this->files->put($path, $content);
        $this->info("前端路由 [ {$this->title} ] 删除成功");
    }

    /**
     * 删除后台菜单
     */
    protected function delAdminMenu(){
        $name = trim($this->name);
        $pluralKebabDummyResource = Str::plural(Str::kebab($name));
        $vueRouter = app(VueRouter::class);
        $parent_id = $vueRouter->where('path', $pluralKebabDummyResource)->value('parent_id');
        $vueRouter->where('id', $parent_id)->delete();
        $vueRouter->where('path', 'like', $pluralKebabDummyResource.'%')->delete();
        $this->info("后台菜单 [ {$this->title} ] 删除成功");
    }

    /**
     * 删除后端路由
     */
    protected function delBackRoute()
    {
        $name = trim($this->name);
        $dummyResource = Str::camel($name);
        $ucDummyResource = Str::ucfirst($dummyResource);
        $pluralKebabDummyResource = Str::plural(Str::kebab($name));
        $controller = "C\\".$ucDummyResource."Controller::class";
        $path = "routes/admin.php";
        $replace = PHP_EOL."Route::resource('{$pluralKebabDummyResource}', $controller);";
        $content = $this->files->get($path);
        $content = str_replace($replace, '', $content);
        $this->files->put($path, $content);
        $this->info("后端路由 [ {$this->title} ] 删除成功");
    }

    /**
     * 删除后台权限
     */
    protected function delAdminPermission()
    {
        $name = trim($this->name);
        $pluralKebabDummyResource = Str::plural(Str::kebab($name));
        $adminPermissionList = [
            'pass-post-'.$pluralKebabDummyResource,
            'pass-delete-'.$pluralKebabDummyResource,
            'pass-put-'.$pluralKebabDummyResource,
            'pass-get-'.$pluralKebabDummyResource
        ];
        $adminPermission = app(AdminPermission::class);
        $adminPermission->whereIn('slug',$adminPermissionList)->delete();
        $this->info("后台权限 [ {$this->title} ] 删除成功");
    }

    /**
     * 删除迁移文件
     */
    protected function delMigration()
    {
        $name = trim($this->name);
        $pluralKebabDummyResource = Str::plural(Str::kebab($name));
        $singularName = barToUnderline( $pluralKebabDummyResource);
        exec('find ./ -type f -iname "*'.$singularName.'*" -delete');
        $this->info("迁移文件 [ {$this->title} ] 删除成功");
    }
}
